package app.fichajes.utils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.os.CountDownTimer;
import android.widget.TextView;



public class CuentaAtras extends CountDownTimer {

	private TextView textViewCounter;
	private static CuentaAtras cuentaAtras;

	private static final long daysInsteadMilliseconds = 86400000;
	private static final long hoursInsteadMilliseconds = 3600000;
	private static final long minutesInsteadMilliseconds = 60000;
	private static final long secondsInsteadMilliseconds = 1000;
	
	public static CuentaAtras getInstance(TextView textViewCount) {
		if(cuentaAtras==null){
			cuentaAtras = new CuentaAtras(tiempoRestanteParaEvento(), 1000, textViewCount);
			cuentaAtras.start();
		}else
		{
			if (textViewCount != null)
				cuentaAtras.textViewCounter = textViewCount;
		}
		return cuentaAtras;
	}
	
	private CuentaAtras(long millisInFuture, long countDownInterval,
			TextView textViewCounter) {
		super(millisInFuture, countDownInterval);
		this.textViewCounter = textViewCounter;
	}
	
	@Override
	public void onFinish() {
	}
	
	@Override
	public void onTick(long millisUntilFinished) {
		// Days
		long day = millisUntilFinished / daysInsteadMilliseconds;
		millisUntilFinished = millisUntilFinished - (day*daysInsteadMilliseconds);
		// Hours
		long hour = millisUntilFinished / hoursInsteadMilliseconds;
		millisUntilFinished = millisUntilFinished - (hour*hoursInsteadMilliseconds);
		// Minuts
		long minute = millisUntilFinished / minutesInsteadMilliseconds;
		millisUntilFinished = millisUntilFinished - (minute*minutesInsteadMilliseconds);
		// Seconds
		long second = millisUntilFinished / secondsInsteadMilliseconds;
		
		final String count = String.valueOf(day) + "d " + String.valueOf(hour) + "h " + String.valueOf(minute) + "m " + String.valueOf(second) + "s";
		try{
			
			textViewCounter.setText(count);	
			textViewCounter.refreshDrawableState();
					
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public TextView getTextViewCounter() {
		return textViewCounter;
	}
	
	public void setTextViewCounter(TextView textViewCounter) {
		this.textViewCounter = textViewCounter;
	}
	
	public void reset() {
		this.cancel();
		cuentaAtras = null;
	}

	
	
	public static long tiempoRestanteParaEvento() {
		
		Calendar calendarPhone = new GregorianCalendar();
		calendarPhone.set(2, calendarPhone.get(2)+1);
		
		Calendar eventoProx = null;
		
		try {
			//31 de agosto a las 12 que seria 1 de septiembre
			
			eventoProx = new GregorianCalendar(); 
			eventoProx.set(2011,8,31,23,59,59);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		//eventoProx = FormatCalendar.changeCalendar(eventoProx);
		//TODO: ojo con la correccion de fecha
		return (eventoProx.getTimeInMillis() - calendarPhone.getTimeInMillis());
	
	}
	
	
	
}
